package com.blb.bookms.dao.impl;

import com.blb.bookms.dao.BookDAO;
import com.blb.bookms.entity.Book;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class BookDAOImpl implements BookDAO {

    private List<Book> books = new ArrayList<>();

    {
        books.add(new Book(1L,"三国演义","罗贯中",44.4,"xx.jpg"));
        books.add(new Book(2L,"水浒传","施耐庵",44.4,"xx.jpg"));
        books.add(new Book(3L,"西游记","吴承恩",44.4,"xx.jpg"));
    }

    @Override
    public List<Book> selectAll() {
        return books;
    }

    @Override
    public Book selectById(Long id) {
        return books.stream().filter(book -> book.getId().equals(id)).collect(Collectors.toList()).get(0);
    }

    @Override
    public void insert(Book book) {
        books.add(book);
    }

    @Override
    public void update(Book book) {
        //通过id查找到的书籍
        Book book1 = books.stream()
                .filter(book2 -> book2.getId().equals(book.getId()))
                .collect(Collectors.toList()).get(0);
        //将新书籍信息赋值给查找到的书籍
        BeanUtils.copyProperties(book,book1);
    }

    @Override
    public void delete(Long id) {
        for(int i = 0;i < books.size();i++){
            if(books.get(i).getId().equals(id)){
                books.remove(i);
                break;
            }
        }
    }
}
